import torch.nn as nn

class LeNet5(nn.Module):
    """LeNet-5模型定义 (对应论文实验部分)"""
    def __init__(self, num_channels=1, num_classes=10):
        super(LeNet5, self).__init__()
        # MNIST: num_channels=1, CIFAR-10: num_channels=3
        self.conv1 = nn.Conv2d(num_channels, 6, 5, padding=2)  # 添加padding保持尺寸
        self.pool1 = nn.MaxPool2d(2)
        self.conv2 = nn.Conv2d(6, 16, 5)
        self.pool2 = nn.MaxPool2d(2)
        self.fc1 = nn.Linear(16*5*5, 120)  # CIFAR-10输入为32x32，经过两次池化后为5x5
        self.fc2 = nn.Linear(120, 84)
        self.fc3 = nn.Linear(84, num_classes)
        
        # 初始化权重 (对应论文实验设置)
        self._initialize_weights()

    def forward(self, x):
        x = self.pool1(nn.functional.relu(self.conv1(x)))
        x = self.pool2(nn.functional.relu(self.conv2(x)))
        x = x.view(x.size(0), -1)  # 展平
        x = nn.functional.relu(self.fc1(x))
        x = nn.functional.relu(self.fc2(x))
        x = self.fc3(x)
        return x
    
    def _initialize_weights(self):
        """权重初始化 (对应论文MNIST实验设置)"""
        for m in self.modules():
            if isinstance(m, nn.Linear):
                # 全连接层权重设为1×10⁵ (论文实验设置)
                nn.init.constant_(m.weight, 1e5)
                nn.init.constant_(m.bias, 0)
            elif isinstance(m, nn.Conv2d):
                nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')
